#!/bin/sh
#
# Update NTP sources from config.json
#

set -e

. /usr/sbin/balena-config-vars

SERVER_DIR=/run/chrony
SERVER_FILE=${SERVER_DIR}/added_config.sources

if [ ! -f "$CONFIG_PATH" ]; then
	echo "balena-ntp-config: $CONFIG_PATH does not exist."
	exit 1
else
	echo "balena-ntp-config: Found config.json in $CONFIG_PATH ."
fi

if [ ! -d "$SERVER_DIR" ]; then
	mkdir -p $SERVER_DIR -m 770
fi

# Always remove the old server file before we refresh the list.
if [ -f "$SERVER_FILE" ]; then
	rm -f $SERVER_FILE
fi

if [ ! -z "$NTP_SERVERS" ]; then
	echo "Adding NTP sources (config.json)"
	for server in ${NTP_SERVERS}; do
		echo "pool $server iburst minpoll 14 maxpoll 14 maxsources 1" >> $SERVER_FILE
	done
fi

# Always update the sources as they may have been added or removed.
/usr/libexec/chrony-helper update-sources || true

exit 0
